//
//  LoginController.m
//  MangoShangJia
//
//  Created by Macbook on 1/8/17.
//  Copyright © 2017年 dazhou. All rights reserved.
//

#import "LoginController.h"
#import "HomePageViewController.h"
#import "RegisterController.h"
#import "ForgetPasswordViewController.h"
//#import "MobLandingViewController.h"
//#import "MixChosseViewController.h"
@interface LoginController ()<UITextFieldDelegate,MBProgressHUDDelegate>
{
    MBProgressHUD *_HUD;

    NSString *_guid;
    NSString *_name;
}
@property (weak, nonatomic) IBOutlet UITextField *AccountFiled;
@property (weak, nonatomic) IBOutlet UITextField *PassFiled;

@end

@implementation LoginController
- (void)viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];

//    _AccountFiled.text = PersonInfoManager.mobile;
//    _PassFiled.text = [DESManeager decryptUseDES:PersonInfoManager.password];
//    _AccountFiled.delegate = self;
//    _PassFiled.delegate = self;
    NSString *lphone = [USERDEFAULT objectForKey:@"mobile"];
    NSString *lPassword = [USERDEFAULT objectForKey:@"password"];
    if (lphone==NULL) {
        NSString *AcountText = @"请输入账户";
        NSMutableAttributedString *AcountPlaceholder = [[NSMutableAttributedString alloc] initWithString:AcountText];
        [AcountPlaceholder addAttribute:NSForegroundColorAttributeName
                                  value:[UIColor whiteColor]
                                  range:NSMakeRange(0, AcountText.length)];
        [AcountPlaceholder addAttribute:NSFontAttributeName
                                  value:[UIFont boldSystemFontOfSize:15]
                                  range:NSMakeRange(0, AcountText.length)];
        _AccountFiled.attributedPlaceholder = AcountPlaceholder;
        
        NSString *PassText = @"请输入密码";
        NSMutableAttributedString *PassPlaceholder = [[NSMutableAttributedString alloc] initWithString:PassText];
        [PassPlaceholder addAttribute:NSForegroundColorAttributeName
                                value:[UIColor whiteColor]
                                range:NSMakeRange(0, PassText.length)];
        [PassPlaceholder addAttribute:NSFontAttributeName
                                value:[UIFont boldSystemFontOfSize:15]
                                range:NSMakeRange(0, PassText.length)];
        _PassFiled.attributedPlaceholder = PassPlaceholder;

        
    }else{
        _AccountFiled.text = lphone;
        _PassFiled.text = lPassword;
        _PassFiled.secureTextEntry = YES;
    }
   
    
}

- (IBAction)ForgetBut:(id)sender
{
    ForgetPasswordViewController* forgetVC = [[ForgetPasswordViewController alloc]init];
    forgetVC.status = @"1";
    [self.navigationController pushViewController:forgetVC animated:YES];
}
- (IBAction)RegistBut:(id)sender
{
    RegisterController* registVC = [[RegisterController alloc]init];
    [self.navigationController pushViewController:registVC animated:YES];

}

- (IBAction)LandingBut:(id)sender
{
    [self tryLogin];

}
- (BOOL)checkRightAll
{
    if (_AccountFiled.text.length > 0 && _PassFiled.text.length > 0) {
        return YES;
    }
    
    return NO;
}
- (void)tryLogin
{
    if ([self checkRightAll] == NO) {
        [self.view makeToast:@"请输入正确的手机号"];
        return;
    }
    _HUD=[MBProgressHUD showHUDAddedTo:self.view animated:YES];
    _HUD.mode=MBProgressHUDModeIndeterminate;//枚举类型不同的效果
    _HUD.delegate = self;
    _HUD.labelText=@"正在登陆";
  
    AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
    manger.responseSerializer = [AFJSONResponseSerializer serializer];
    manger.requestSerializer = [AFJSONRequestSerializer serializer];
    manger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/ttml", nil];
    NSString *Url = [NSString stringWithFormat:@"%@%@",ServiceURL2,req_login];
//    NSString *password = [YBRequestManager getMd5:_PassFiled.text];
    NSString *pa = [DESManeager encryptUseDES:_PassFiled.text];
    NSDictionary *params = @{@"mobile":_AccountFiled.text,@"password":pa};
 

    
    [manger POST:Url parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = responseObject[@"data"];
        NSString *code = responseObject[@"code"];
        _guid = dict[@"guid"];
        _name = dict[@"name"];
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:dict[@"mobile"] forKey:@"mobile"];
        [userDefaults setObject:_name forKey:@"name"];
        [userDefaults setObject:dict[@"summary"] forKey:@"summary"];
        [userDefaults setObject:dict[@"token"] forKey:@"token"];
        [userDefaults setObject:dict[@"guid"] forKey:@"shop_guid"];
        [userDefaults setObject:dict[@"headImage"] forKey:@"head_image"];
        [userDefaults setObject:_PassFiled.text forKey:@"password"];
        [USERDEFAULT setBool:YES forKey:@"isLogin"];
        [userDefaults synchronize];
        [self performSelectorOnMainThread:@selector(delayMe) withObject:nil waitUntilDone:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        [self performSelectorOnMainThread:@selector(delayMe2) withObject:nil waitUntilDone:YES];
    }];
//
}

-(void)delayMe{
//    EMError *error2 = [[EMClient sharedClient] registerWithUsername:_guid password:@"123456"];
//    if (error2==nil) {
//        NSLog(@"注册成功");
//    }
    EMError *error = [[EMClient sharedClient] loginWithUsername:_guid password:@"123456"];
    if (!error)
    {
        NSLog(@"登录成功");
        [[EMClient sharedClient].options setIsAutoLogin:YES];
    }
     [MBProgressHUD hideHUDForView:self.view animated:YES];
    HomePageViewController *home = [[HomePageViewController alloc]init];
    [self.navigationController pushViewController:home animated:YES];



//    [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:_guid password:@"123456" completion:^(NSDictionary *loginInfo, EMError *error) {
//        if (!error && loginInfo) {
//            NSLog(@"环信登录成功");
//            // 设置消息显示类型
//            EMPushNotificationOptions *options = [[EaseMob sharedInstance].chatManager pushNotificationOptions];
//            options.displayStyle = ePushNotificationDisplayStyle_messageSummary;
//            if (_name && _name.length > 0) {
//                options.nickname = _name;
//            } else {
//                options.nickname = _guid;
//            }
//            [[EaseMob sharedInstance].chatManager asyncUpdatePushOptions:options];
//            //设置推送设置
//            [[EaseMob sharedInstance].chatManager setApnsNickname:options.nickname];
//            
//        } else {
//            NSLog(@"环信登录失败:%@",error.description);
//        }
//    } onQueue:nil];
//    
//    [[LoginManager Instance] showMainView];
}
-(void)delayMe2{
     [MBProgressHUD hideHUDForView:self.view animated:YES];
    [self.view makeToast:@"登录失败"];
}
//- (void)handleErrorResp:(HttpMessage *)msg
//{
//    [self.view showProgressOnlyLabel:@"登录失败"];
//}

- (IBAction)GuangGuangBut:(id)sender
{
    NSLog(@"随便逛逛");

}
- (IBAction)MobLandingBut:(id)sender {
//    MobLandingViewController* MobLan = [[MobLandingViewController alloc]init];
//    [self.navigationController pushViewController:MobLan animated:YES];
    NSLog(@"手机登陆");
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches   withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
